package com.android.delivery.activity

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.android.delivery.R
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseActivity
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.constant.SputilsConstant
import com.android.delivery.entity.Addr
import com.android.delivery.entity.AreaBean
import com.android.delivery.util.GsonUtil
import com.android.delivery.util.ToastUtils
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SPUtils
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions3.RxPermissions
import com.tencent.lbssearch.TencentSearch
import com.tencent.lbssearch.`object`.param.DistrictChildrenParam
import com.tencent.lbssearch.`object`.result.DistrictResultObject
import com.tencent.lbssearch.`object`.result.SuggestionResultObject
import com.tencent.lbssearch.httpresponse.BaseObject
import com.tencent.map.tools.net.http.HttpResponseListener
import kotlinx.android.synthetic.main.activity_add_addr.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @author: mqwang
 * @create: 2/10/21 1:00 AM
 * @Description: 新增/编辑-收货地址
 */
class AddAddrActivity : BaseActivity() {

    private var adcode: String? = null
    private var item: Addr? = null
    private var mOpt1tx: String? = null
    private var mOpt2tx: String? = null
    private var mOpt3tx: String? = null
    private var latitude: Double? = 0.0
    private var longitude: Double? = 0.0
    private var mStreetArea: AreaBean? = null
    private var options1Items: ArrayList<AreaBean> = ArrayList<AreaBean>()
    private val options2Items = ArrayList<ArrayList<AreaBean>>()
    private val options3Items: ArrayList<ArrayList<ArrayList<AreaBean>>> = ArrayList()
    private var mStreetId: Int = 0
    private var mProvinceList: ArrayList<AreaBean>? = null
    var mCurrProvinceP: Int = 0
    var mCurrCityP: Int = 0
    var mCurrAreaP: Int = 0
    var mAddrDialog: OptionsPickerView<AreaBean>? = null
    var mStreetDialog: OptionsPickerView<AreaBean>? = null

    companion object {
        fun self(context: Context?) {
            val intent = Intent(context, AddAddrActivity::class.java)
            context!!.startActivity(intent)
        }

        fun self(context: Context?, addr: Addr) {
            val intent = Intent(context, AddAddrActivity::class.java)
            intent.putExtra(Constants.ITEM, addr)
            context!!.startActivity(intent)
        }

        fun self(context: Activity?, addr: Addr, requestCode: Int) {
            val intent = Intent(context, AddAddrActivity::class.java)
            intent.putExtra(Constants.ITEM, addr)
            context!!.startActivityForResult(intent, requestCode)
        }
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_add_addr
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {
        setMainTitle("地址")

        item = intent!!.getParcelableExtra(Constants.ITEM)

        if (item != null) {
            et_name.setText(item!!.name)
            et_name.setSelection(item!!.name.length)
            et_phone.setText(item!!.mobile)
            tv_addr_select.setText(item!!.province + item!!.city + item!!.district)
            tv_street_select.setText(item!!.street)
            tv_addr_info.setText(item!!.address)
            mOpt2tx = item!!.city
            latitude = item!!.latitude
            longitude = item!!.longitude
        }

        tv_addr_select.setOnClickListener {
            KeyboardUtils.hideSoftInput(it)
            getProvinceAndShow()
        }

        tv_street_select.setOnClickListener {
            KeyboardUtils.hideSoftInput(it)

            if (mStreetId == 0) {
                ToastUtils.showShort(this, "请先选择地址")
                return@setOnClickListener
            }
            val tencentSearch = TencentSearch(this)
            val districtChildrenParam = DistrictChildrenParam()
            districtChildrenParam.id(mStreetId)
            tencentSearch.getDistrictChildren(districtChildrenParam, object : HttpResponseListener<BaseObject> {
                override fun onSuccess(p0: Int, p1: BaseObject?) {
                    val district: DistrictResultObject = p1 as DistrictResultObject
                    showStreetPickerView(district.result.get(0))
                }

                override fun onFailure(p0: Int, p1: String?, p2: Throwable?) {
                    ToastUtils.showShort(this@AddAddrActivity, p1)
                }
            })
        }

        tv_confirm.setOnClickListener {
            var name = et_name.text.toString()
            var phone = et_phone.text.toString()
            var addr = tv_addr_select.text.toString()
            var street = tv_street_select.text.toString()
            var addr_info = tv_addr_info.text.toString()

            if (TextUtils.isEmpty(name)) {
                ToastUtils.showShort(this, "请输入收件人")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showShort(this, "请输入联系电话")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(addr)) {
                ToastUtils.showShort(this, "请选择地址")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(street)) {
                ToastUtils.showShort(this, "请选择街道")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(addr_info)) {
                ToastUtils.showShort(this, "请输入详细地址")
                return@setOnClickListener
            }

            if (item != null) {
                ApiService.user_address(this, adcode, item!!.id, addr_info, mOpt2tx, mOpt3tx, latitude, longitude, phone, name, mOpt1tx, street, object : DialogCallback<LzyResponse<Any>>(this) {
                    override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                        ToastUtils.showShort(this@AddAddrActivity, getString(R.string.success))
                        setResult(Activity.RESULT_OK)
                        finish()
                    }

                })
            } else {
                ApiService.user_address(this, adcode, addr_info, mOpt2tx, mOpt3tx, latitude, longitude, phone, name, mOpt1tx, street, object : DialogCallback<LzyResponse<Any>>(this) {
                    override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                        ToastUtils.showShort(this@AddAddrActivity, getString(R.string.success))

                        var addr = Addr()
                        addr.adcode = adcode
                        addr.province = mOpt1tx
                        addr.city = mOpt2tx
                        addr.district = mOpt3tx
                        addr.street = mStreetArea?.pickerViewText
                        addr.address = addr_info
                        addr.name = name
                        addr.mobile = phone
                        if (latitude != null) {
                            addr.latitude = latitude!!
                        }
                        if (longitude != null) {
                            addr.longitude = longitude!!
                        }
                        EventBus.getDefault().post(addr)
                        setResult(Activity.RESULT_OK)
                        finish()
                    }

                })
            }
        }

        val provinceStr = SPUtils.getInstance().getString(SputilsConstant.PROVINCE)
        val provinceList = GsonUtil.parseList<AreaBean>(provinceStr, object : TypeToken<ArrayList<AreaBean>>() {}.type)
        if (provinceList == null || provinceList.isEmpty()) {
            getProvinceDataFromMap(false)
        } else {
            mProvinceList = provinceList as ArrayList<AreaBean>
            formateProvinceData(mProvinceList!!)
        }
    }

    private fun showStreetPickerView(streetList: List<DistrictResultObject.DistrictResult>) {
        if (mStreetDialog == null) {
            var areaList = ArrayList<AreaBean>()
            for (street in streetList) {
                var areaBean = AreaBean()
                areaBean.id = street.id
                areaBean.name = street.fullname
                areaBean.latLng = street.latLng
                areaList.add(areaBean)
            }
            mStreetDialog = OptionsPickerBuilder(this) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
                mStreetArea = areaList.get(options1)
                latitude = mStreetArea?.latLng?.latitude
                longitude = mStreetArea?.latLng?.longitude
                tv_street_select.setText(mStreetArea?.pickerViewText)
            }
                    .setTitleText("街道选择")
                    .setDividerColor(Color.BLACK)
                    .setCancelColor(resources.getColor(R.color.colorAccent))
                    .setSubmitColor(resources.getColor(R.color.colorAccent))
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(18)
                    .build<AreaBean>()

            /*pvOptions.setPicker(options1Items);//一级选择器
            pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
            mStreetDialog?.setPicker(areaList)
            mStreetDialog?.setSelectOptions(getStreetP(areaList))
        }
        mStreetDialog?.show()
    }

    private fun getStreetP(areaList: ArrayList<AreaBean>): Int {
        if (item != null) {
            for (index in 0..areaList.size - 1) {
                val itemIndex = areaList.get(index)
                if (TextUtils.equals(itemIndex.name, item!!.street)) {
                    return index
                }
            }
        }
        return 0
    }

    private fun getProvinceAndShow() {
        val rxPermissions = RxPermissions(this) // where this is an Activity or Fragment instance
        rxPermissions
                .request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe { granted: Boolean ->
                    if (granted) { // Always true pre-M
                        if (mProvinceList.isNullOrEmpty()) {
                            val provinceStr = SPUtils.getInstance().getString(SputilsConstant.PROVINCE)
                            mProvinceList = com.ada.common.util.GsonUtil.parseList<AreaBean>(provinceStr, object : TypeToken<ArrayList<AreaBean>>() {}.type) as ArrayList<AreaBean>?
                            if (mProvinceList != null && !mProvinceList!!.isEmpty()) {
                                formateProvinceData(mProvinceList!!)
                                showPickerView()
                            } else {
                                getProvinceDataFromMap(true)
                            }
                        } else {
                            formateProvinceData(mProvinceList!!)
                            showPickerView()
                        }
                    }
                }
    }

    private fun getProvinceDataFromMap(isShow: Boolean) {
        val tencentSearch = TencentSearch(this)
        tencentSearch.getDistrictList(object : HttpResponseListener<BaseObject> {
            override fun onSuccess(p0: Int, p1: BaseObject?) {
                val district: DistrictResultObject = p1 as DistrictResultObject
                val province = district.result.get(0)
                val city = district.result.get(1)
                val street = district.result.get(2)

                var provinceList = ArrayList<AreaBean>()
                for (result in province) {
                    var jsonBean = AreaBean()
                    jsonBean.id = result.id
                    jsonBean.name = result.fullname

                    //补全城市
                    var cityList = ArrayList<AreaBean>()
                    val subCityList = city.subList(result.cidx[0], result.cidx[1] + 1)

                    if (subCityList.get(0).cidx == null) {
                        //城市下一级为空，表示省即是市
                        var cityBean = AreaBean()
                        cityBean.id = result.id
                        cityBean.name = result.fullname

                        var areaList = ArrayList<AreaBean>()
                        for (cityResult in subCityList) {
                            var areaBean = AreaBean()
                            areaBean.id = cityResult.id
                            areaBean.name = cityResult.fullname
                            areaList.add(areaBean)
                        }
                        cityBean.subList = areaList
                        cityList.add(cityBean)
                    } else {
                        for (cityResult in subCityList) {
                            var cityBean = AreaBean()
                            cityBean.id = cityResult.id
                            cityBean.name = cityResult.fullname

                            //补全地区
                            var areaList = ArrayList<AreaBean>()
                            if (cityResult.cidx == null) {
                                var areaBean = AreaBean()
                                areaBean.id = cityResult.id
                                areaBean.name = cityResult.fullname
                                areaList.add(areaBean)
                            } else {
                                val subAreaList = street.subList(cityResult.cidx[0], cityResult.cidx[1] + 1)
                                for (areaResult in subAreaList) {
                                    var areaBean = AreaBean()
                                    areaBean.id = areaResult.id
                                    areaBean.name = areaResult.fullname
                                    areaList.add(areaBean)
                                }
                            }
                            cityBean.subList = areaList
                            cityList.add(cityBean)
                        }
                    }

                    jsonBean.subList = cityList
                    provinceList.add(jsonBean)
                }
                SPUtils.getInstance().put(SputilsConstant.PROVINCE, GsonUtil.toJson(provinceList))
                mProvinceList = provinceList

                if (isShow) {
                    formateProvinceData(provinceList)
                    showPickerView()
                }
            }

            override fun onFailure(p0: Int, p1: String?, p2: Throwable?) {
                ToastUtils.showShort(this@AddAddrActivity, p1)
            }
        })
    }

    private fun formateProvinceData(provinceList: ArrayList<AreaBean>) {
        //判断数据是否为空
        if (options1Items.isNullOrEmpty() || options2Items.isNullOrEmpty() || options3Items.isNullOrEmpty()) {
            //业务邀请只需要福建省
            val filiterProvince = filiterProvince(provinceList)
            for (result in filiterProvince) {
                options1Items.add(result)

                val subList = result.subList
                var filiterSubList = ArrayList<AreaBean>()
                var filiterSubChildList = ArrayList<ArrayList<AreaBean>>()
                for (subResult in subList) {
                    if (TextUtils.equals(subResult.name, "漳州市") || TextUtils.equals(subResult.name, "厦门市")) {
                        //业务只需要漳州市/厦门市
                        filiterSubList.add(subResult)
                        filiterSubChildList.add(subResult.subList)
                    }
                }
                options2Items.add(filiterSubList)
                options3Items.add(filiterSubChildList)
            }
        }

        mCurrProvinceP = getProvinceP()
        mCurrCityP = getCityP(mCurrProvinceP)
        mCurrAreaP = getAreaP(mCurrProvinceP, mCurrCityP)
    }

    /**
     * 业务范围只需要福建省
     */
    private fun filiterProvince(provinceList: ArrayList<AreaBean>): ArrayList<AreaBean> {
        var provinceDatas = ArrayList<AreaBean>()
        for (result in provinceList) {
            if (TextUtils.equals(result.name, "福建省")) {
                provinceDatas.add(result)
                return provinceDatas
            }
        }
        return provinceList
    }


    private fun showPickerView() { // 弹出选择器
        if (mAddrDialog == null) {
            mAddrDialog = OptionsPickerBuilder(this) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
                var opt1tx = if (options1Items.size > 0) options1Items[options1].pickerViewText else ""
                var opt2tx = if (options2Items.size > 0
                        && options2Items[options1].size > 0) options2Items[options1][options2].pickerViewText else ""
                var opt3tx = if (options2Items.size > 0 && options3Items[options1].size > 0 && options3Items[options1][options2].size > 0) options3Items[options1][options2][options3].pickerViewText else ""
                val tx = opt1tx + opt2tx + opt3tx
                this.mOpt1tx = opt1tx
                this.mOpt2tx = opt2tx
                this.mOpt3tx = opt3tx
                var streetId = options3Items[options1][options2][options3].id
                if (mStreetId != streetId) {
                    mStreetId = streetId
                    tv_street_select.setText("")
                    mStreetDialog = null
                }

                tv_addr_select.setText(tx)
            }
                    .setTitleText("城市选择")
                    .setDividerColor(Color.BLACK)
                    .setCancelColor(resources.getColor(R.color.colorAccent))
                    .setSubmitColor(resources.getColor(R.color.colorAccent))
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(18)
                    .build<AreaBean>()

            /*pvOptions.setPicker(options1Items);//一级选择器
            pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
            mAddrDialog?.setPicker(options1Items, options2Items as List<MutableList<AreaBean>>, options3Items as List<MutableList<MutableList<AreaBean>>>) //三级选择器
            mAddrDialog?.setSelectOptions(mCurrProvinceP, mCurrCityP, mCurrAreaP)
        }
        mAddrDialog?.show()
    }

    private fun getAreaP(provinceP: Int, cityP: Int): Int {
        if (item != null) {
            val cityList = options3Items.get(provinceP)
            val areaList = cityList.get(cityP)
            for (index in 0..areaList.size - 1) {
                val itemIndex = areaList.get(index)
                if (TextUtils.equals(itemIndex.name, item!!.district)) {
                    mStreetId = itemIndex.id
                    return index
                }
            }
        }
        return 0
    }

    private fun getCityP(provinceP: Int): Int {
        if (item != null) {
            val cityList = options2Items.get(provinceP)
            for (index in 0..cityList.size - 1) {
                val itemIndex = cityList.get(index)
                if (TextUtils.equals(itemIndex.name, item!!.city)) {
                    return index
                }
            }
        }
        return 0
    }

    private fun getProvinceP(): Int {
        if (item != null) {
            for (index in 0..options1Items.size - 1) {
                val itemIndex = options1Items.get(index)
                if (TextUtils.equals(itemIndex.name, item!!.province)) {
                    return index
                }
            }
        }
        return 0
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun selectAddr(addr: SuggestionResultObject.SuggestionData) {
        adcode = addr.adcode
        item!!.latitude = addr.latLng.latitude
        item!!.longitude = addr.latLng.longitude
        tv_addr_info.setText(addr.address)

    }
}